/**
 * 缓存管理工具
 * 提供课程表数据的本地缓存功能
 */

import { ClassCoursesResponse } from '@/types/api';
import localStorageKeys from './localStorageKeys';

/** 缓存数据结构 */
interface CachedCourseData {
  school_id: number;
  class_code: string;
  data: ClassCoursesResponse;
  timestamp: number;
}

/** 缓存配置 */
const CACHE_CONFIG = {
  /** 缓存键名 */
  CACHE_KEY: localStorageKeys.cache_courses,
  /** 缓存开关键名 */
  USE_CACHE_KEY: localStorageKeys.use_course_cache,
  /** 缓存有效期(24小时,单位:毫秒) */
  CACHE_DURATION: 24 * 60 * 60 * 1000,
};

/**
 * 检查是否启用缓存
 */
export const isCacheEnabled = (): boolean => {
  try {
    const value = localStorage.getItem(CACHE_CONFIG.USE_CACHE_KEY);
    // 如果未设置,默认启用缓存
    if (value === null) {
      setCacheEnabled(true);
      return true;
    }
    return value === 'true';
  } catch {
    return false;
  }
};

/**
 * 设置缓存开关
 */
export const setCacheEnabled = (enabled: boolean): void => {
  try {
    localStorage.setItem(CACHE_CONFIG.USE_CACHE_KEY, enabled ? 'true' : 'false');
  } catch (error) {
    console.error('Failed to set cache enabled:', error);
  }
};

/**
 * 获取缓存的课程表数据
 * @param school_id - 学校ID
 * @param class_code - 班级编号
 * @returns 缓存的数据,如果不存在或已过期则返回null
 */
export const getCachedCourseData = (
  school_id?: number,
  class_code?: string
): CachedCourseData | null => {
  // 如果未启用缓存,直接返回null
  if (!isCacheEnabled()) {
    return null;
  }

  try {
    const cached = localStorage.getItem(CACHE_CONFIG.CACHE_KEY);
    if (!cached) return null;

    const data: CachedCourseData = JSON.parse(cached);

    // 检查缓存是否过期(超过24小时)
    const now = Date.now();
    if (now - data.timestamp > CACHE_CONFIG.CACHE_DURATION) {
      // 缓存已过期,清除并返回null
      clearCourseCache();
      return null;
    }

    // 如果提供了参数,检查是否匹配
    if (school_id !== undefined && data.school_id !== school_id) {
      return null;
    }
    if (class_code !== undefined && data.class_code !== class_code) {
      return null;
    }

    return data;
  } catch (error) {
    console.error('Failed to get cached course data:', error);
    return null;
  }
};

/**
 * 保存课程表数据到缓存
 * @param school_id - 学校ID
 * @param class_code - 班级编号
 * @param data - 课程表数据
 */
export const setCachedCourseData = (
  school_id: number,
  class_code: string,
  data: ClassCoursesResponse
): void => {
  try {
    const cacheData: CachedCourseData = {
      school_id,
      class_code,
      data,
      timestamp: Date.now(),
    };
    localStorage.setItem(CACHE_CONFIG.CACHE_KEY, JSON.stringify(cacheData));
  } catch (error) {
    console.error('Failed to cache course data:', error);
  }
};

/**
 * 清除课程表缓存
 */
export const clearCourseCache = (): void => {
  try {
    localStorage.removeItem(CACHE_CONFIG.CACHE_KEY);
  } catch (error) {
    console.error('Failed to clear course cache:', error);
  }
};

/**
 * 获取缓存的学校ID和班级编号
 * @returns 缓存的school_id和class_code,如果不存在则返回undefined
 */
export const getCachedSelection = (): {
  school_id?: number;
  class_code?: string;
} => {
  const cached = getCachedCourseData();
  if (!cached) return {};

  return {
    school_id: cached.school_id,
    class_code: cached.class_code,
  };
};
